package org.example.dyscript.dynamicscript;


import lombok.SneakyThrows;
import org.example.dyscript.generator.EvaluateRule;
import org.example.dyscript.generator.FullyQualifiedJavaType;
import org.example.dyscript.generator.JavaClassGenerator;

import java.util.HashMap;
import java.util.Map;

public class JavaDynamicClassRule implements Rule {

  EvaluateRule executeRule = null;
  EvaluateRule evaluateRule = null;

  @SneakyThrows
  public JavaDynamicClassRule() {

    String executeFullClassName = "org.example.dyscript.execute.JavaHHHRule";

    Map<String, FullyQualifiedJavaType> executeRuleParametersTypeMap = new HashMap<>();
    executeRuleParametersTypeMap.put("ali_score", new FullyQualifiedJavaType("Integer"));
    executeRuleParametersTypeMap.put("wx_score", new FullyQualifiedJavaType("Integer"));
    executeRuleParametersTypeMap.put("pd_living_province", new FullyQualifiedJavaType("String"));
    executeRuleParametersTypeMap.put("pd_census_province", new FullyQualifiedJavaType("String"));

    String executeExpression = "ali_score > 100 && wx_score < 450 && !pd_living_province.contains(\"乌克兰\") "
        + "&& pd_census_province.contains(\"吉尔吉斯斯坦\")";

    Class<?> executeClass = JavaClassGenerator.generator(executeFullClassName, executeRuleParametersTypeMap,
        executeExpression);

    // try instance:
    executeRule = (EvaluateRule) executeClass.newInstance();

    String evaluateFullClassName = "org.example.dyscript.JavaHHHRule";

    Map<String, FullyQualifiedJavaType> evaluateRuleParametersTypeMap = new HashMap<>();
    evaluateRuleParametersTypeMap.put("age", new FullyQualifiedJavaType("Integer"));
    evaluateRuleParametersTypeMap.put("vip", new FullyQualifiedJavaType("String"));

    String evaluateExpression = "age > 18 && vip.contains(\"vip\")";

    Class<?> evaluateClass = JavaClassGenerator.generator(evaluateFullClassName, evaluateRuleParametersTypeMap,
        evaluateExpression);

    // try instance:
    evaluateRule = (EvaluateRule) evaluateClass.newInstance();
  }

  @Override
  public boolean execute(Map<String, Object> parameters) {
    return executeRule.evaluate(parameters);
  }

  @Override
  public boolean evaluate(Map<String, Object> parameters) {
    return evaluateRule.evaluate(parameters);
  }
}
